/*
 * @Description: 
 * @Author: Jinzhu Liu
 * @Date: 2021-12-15 22:53:22
 * @LastEditor: Jinzhu Liu
 * @LastEditTime: 2021-12-19 22:11:13
 */
import { Rules } from "async-validator"
import { Context } from "koa"
import { type } from "os"
import { sign } from "../../utils/auth"
import response from "../../utils/response"
import validate from "../../utils/validate"
import AdminService from "../service/admin_service"

class LoginController {
    async index(ctx: Context) {
        const rules: Rules = {
            name: [
                {
                    type: 'string',
                    required: true,
                    message: 'User name cannot be empty'
                }
            ],
            password: [
                {
                    type: 'string',
                    required: true,
                    message: 'Password cannot be empty'
                }
            ]
        }

        interface IAdmin {
            name: string,
            password: string
        }
        const { data, error } = await validate<IAdmin>(ctx, rules)
        if (error !== null) {
            return response.error(ctx, error)
        }
        const admin = await AdminService.getAdminByName((data as IAdmin).name)
        if (admin === null) {
            return response.error(ctx, 'Admin not exist', null)
        }

        const token = sign(admin)
        response.success(ctx, { token })
    }
}

export default new LoginController